package com.atguigu.tingshu.handler;

import com.atguigu.tingshu.model.CDCEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

/**
 * Package: com.atguigu.tingshu.handler
 *
 * @description:  
 * @author xiongkunYang
 * @since 2025/6/24 19:35 
 */
@Slf4j
@Component
@CanalTable("user_info") ////监听变更表
public class UserCdcHandler implements EntryHandler<CDCEntity> {

    private final RedisTemplate<Object, Object> redisTemplate;

    public UserCdcHandler(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 监听数据库 insert 操作
     * @param cdcEntity 新增的数据
     */
    @Override
    public void insert(CDCEntity cdcEntity) {
        EntryHandler.super.insert(cdcEntity);
    }

    /**
     * 监听数据库 update 修改操作
     *
     * @param before 修改前数据
     * @param after  修改后数据
     */
    @Override
    public void update(CDCEntity before, CDCEntity after) {
        log.info("监听到数据修改,ID:{}", after.getId());
        this.clearCache(after.getId());

    }

    /**
     * 监听数据库 delete 删除操作
     *
     * @param cdcEntity 删除前数据
     */
    @Override
    public void delete(CDCEntity cdcEntity) {
        log.info("监听到数据删除,ID:{}", cdcEntity.getId());
        this.clearCache(cdcEntity.getId());
    }

    /**
     * 清除缓存工具方法
     */
    public void clearCache(Long id) {
        String key = "user:info:" + id;
        this.redisTemplate.delete(key);
    }
}